
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/operation/rb_config.dart';
import 'package:reabampos/src/reabam/ui/support/support_upload_order_paylist.dart';
import 'package:reabampos/src/reabam/ui_self_service/pagestate_ss_login.dart';
import 'package:reabampos/src/reabam/ui_self_service/shoppingcart/pagestate_ss_manual_input_gooditem_barcode_search.dart';
import 'package:reabampos/src/reabam/ui_self_service/shoppingcart/pagestate_ss_pay_result.dart';
import 'package:reabampos/src/reabam/utils/brean/c_bean_good_item.dart';
import 'package:reabampos/src/reabam/utils/rb_business.dart';
import 'package:reabampos/src/reabam/utils/rb_color.dart';
import 'package:reabampos/src/reabam/utils/rb_widget_ss.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_string.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';

/*
支付
 */
class PageStateSelfServicePay extends XPageState{

  bool isPayWaiting=false;

  late XFunctionNotifyStateChangeListener listener_pay;

  PageStateSelfServicePay();

  @override
  void onCreate() {
    super.onCreate();
    RBConfigs.isPageScanType=2;

    listener_pay=(String key,dynamic value){
      //通知支付完成,检查支付结果...
      if('start'==key){
        setState(() {
          isPayWaiting=true;
        });
      }else if('failed'==key){
        setState(() {
          isPayWaiting=false;
        });

      }else{
        //key=orderId
        RBConfigs.isPageScanType=0;
        notifyExitButtonStopTimer(RBConfigs.Tag_action_receive_notify_pay_auto_exit);
        //检查支付结果
        Future((){
          _payResultCheck(
              requestId: key,
              gatheringId: value
          );
        });
      }




    };

    XNotifyStateChangeUtils.receiveChangeNotify(
        action: RBConfigs.NotifyAction_selfService_pay_check,
        listener: listener_pay
    );

  }


  //检查支付结果
  Timer? checkTimer;
  void _payResultCheck(
      {
        required String? requestId,//=orderId
        required String? gatheringId,
      }
      ){

    checkTimer=Timer(const Duration(seconds: 1),(){

      RBBaseApi.pay_check(
          requestId: requestId,
          gatheringId: gatheringId,
          succeed: (response, Map<String, dynamic> responseMap, Map<String, dynamic> headers_response) {

            if(mounted){
              dynamic payStatus=responseMap['data']?['payStatus'];
              if('1'=='$payStatus'){
                notifyExitButtonStopTimer(RBConfigs.Tag_action_receive_notify_pay_wait_check);

                dynamic thPayInfo=responseMap['data']?['thPayInfo'];

                //生成订单
                _createOrderAndUpload(thPayInfo,requestId);


                //通知打印
                XNotifyStateChangeUtils.notifyStateChange(
                    action: RBConfigs.Notify_Global_Handler,
                    key: 'succeedPayPrintOrder',
                    value: requestId
                );

              }else{

                Future((){
                  _payResultCheck(
                      requestId: requestId,
                      gatheringId: gatheringId
                  );
                });


              }

            }

          },
          failed: (String code, String msg) {

            if(mounted){
              Future((){
                _payResultCheck(
                    requestId: requestId,
                    gatheringId: gatheringId
                );
              });
            }

          }
      );

    });



  }

  //生成订单和上传
  void _createOrderAndUpload(dynamic thPayInfo,dynamic orderId){

    showLoading(isOurSideCanClick: false);
    //1.生成订单
    Future((){

      Map<String,dynamic> data={};
      data['fastOrderNo']=orderId;
      data['combTaskId']=XNumberUtils.dynamic2int('${XDateUtils.getCurrentTime_ms()+XNumberUtils.randomInt(10000)}');
      data['companyId']=XSharePreferencesUtils.getString(RBConfigs.SP_companyId);
      data['userId']=XSharePreferencesUtils.getString(RBConfigs.SP_userId);
      data['totalMoney']=XNumberUtils.formatDoubleX(RBBusinessUtils.shoppingcartInfo_selfService['totalMoney']??0, n: 2);
      data['totalQuantity']=RBBusinessUtils.shoppingcartInfo_selfService['totalQuantity']??0;
      data['totalCount']=RBBusinessUtils.shoppingcartInfo_selfService['totalCount']??0;

      List<dynamic> fastOrderTasks=[];

      //1.1订单
      Map<String,dynamic> task1={};
      task1['taskId']=XNumberUtils.dynamic2int('${XDateUtils.getCurrentTime_ms()+XNumberUtils.randomInt(10000)}');
      task1['fastOrderNo']=orderId;
      task1['typeCode']=1;
      task1['pushVersion']=RBConfigs.versionName;
      task1['pushClient']='自助收银';
      //
      Map<String,dynamic> pushJson1={};
      pushJson1['outOrderNo']=orderId;
      pushJson1['realCreateDate']=XDateUtils.getStringTimeFormat();
      pushJson1['docTypeInfo']=XJsonUtils.json2Map(XSharePreferencesUtils.getString(RBConfigs.SP_docTypeInfo));
      pushJson1['staff']=XJsonUtils.json2Map(XSharePreferencesUtils.getString(RBConfigs.SP_staff));
      pushJson1['totalQuantity']=XNumberUtils.formatDoubleX(RBBusinessUtils.shoppingcartInfo_selfService['totalQuantity']??0);
      pushJson1['totalItemQuantity']=XNumberUtils.formatDoubleX(RBBusinessUtils.shoppingcartInfo_selfService['totalQuantity']??0);
      pushJson1['amountActuallyPaid']=XNumberUtils.formatDoubleX(RBBusinessUtils.shoppingcartInfo_selfService['totalMoney']??0, n: 2);
      pushJson1['amountPayable']=XNumberUtils.formatDoubleX(RBBusinessUtils.shoppingcartInfo_selfService['totalMoney']??0, n: 2);
      pushJson1['totalAmount']=XNumberUtils.formatDoubleX(RBBusinessUtils.shoppingcartInfo_selfService['totalMoney']??0, n: 2);
      pushJson1['payType']=RBConfigs.payParentType;
      pushJson1['payTypeName']=RBConfigs.payParentTypeName;
      List<dynamic> items1=[];
      for(ComponentBeanGoodItem iitem in RBBusinessUtils.list_shoppingcart_selfService){

        Map<String,dynamic> itemMap=iitem.toJson();
        itemMap['saleUnitPrice']=iitem.dealPrice;
        itemMap['listUnitPrice']=iitem.dealPrice;
        itemMap['dealUnitPrice']=iitem.dealPrice;
        itemMap['quantity']=iitem.currentQuantity;
        itemMap['actuallyPaid']=iitem.currentMoney;
        itemMap['actuallyUnitPaid']=iitem.currentMoney;

        Map<String,dynamic> dItem={};
        dItem['mainSpecId']=iitem.specId;
        dItem['shopCartItemType']=1;
        dItem['dealPriceAmount']=iitem.dealPrice;
        dItem['productSet']=[];
        dItem['productSet'].add(itemMap);
        //
        items1.add(dItem);
      }
      //
      pushJson1['items']=items1;
      //
      task1['pushJson']=XJsonUtils.obj2Json(pushJson1);


      //1.2支付
      Map<String,dynamic> task2={};
      task2['taskId']=XNumberUtils.dynamic2int('${XDateUtils.getCurrentTime_ms()+XNumberUtils.randomInt(10000)}');
      task2['fastOrderNo']=orderId;
      task2['typeCode']=2;
      task2['pushVersion']=RBConfigs.versionName;
      task2['pushClient']='自助收银';
      Map<String,dynamic> pushJson2={};
      pushJson2['orderType']='order';
      pushJson2['payType']='SpecialFastThPay';
      pushJson2['paycode']=RBConfigs.payParentType;
      pushJson2['payTypeName']=RBConfigs.payParentTypeName;


      //
      Map<String,dynamic> offlinePayParameter={};
      offlinePayParameter['realCreateDate']=XDateUtils.getStringTimeFormat();
      //
      Map<String,dynamic> specialFastThPay={};
      specialFastThPay['dgatheringId']=thPayInfo['id'];
      specialFastThPay['thPayInfo']=thPayInfo;
      offlinePayParameter['specialFastThPay']=specialFastThPay;
      //
      pushJson2['offlinePayParameter']=offlinePayParameter;


      pushJson2['creatDate']=XDateUtils.getStringTimeFormat();
      pushJson2['orderId']=orderId;
      pushJson2['orderNo']=orderId;
      pushJson2['sourceOrderNo']=orderId;
      pushJson2['items']=RBBusinessUtils.list_shoppingcart_selfService;
      pushJson2['payAmount']=XNumberUtils.formatDoubleX(RBBusinessUtils.shoppingcartInfo_selfService['totalMoney']??0, n: 2);
      task2['pushJson']=XJsonUtils.obj2Json(pushJson2);

      //
      fastOrderTasks.add(task1);
      fastOrderTasks.add(task2);
      data['fastOrderTasks']=fastOrderTasks;

      //
      SupportUploadOrderAndPay.uploadOrderTask2(data);

      startPage(PageStateSelfServicePayResult(true),isFinish: true);
    });

  }


  @override
  void onDestroy() {
    super.onDestroy();
    XNotifyStateChangeUtils.unReceiveChangeNotify(
        action: RBConfigs.NotifyAction_selfService_pay_check,
        listener: listener_pay
    );
  }

  @override
  void onStart() {

    setXTopBarWidget(
        height: null,
        child: RBWidgets_SelfService.getTitleBarWidget(
          this,
          title: '付款',
        )
    );

  }

  @override
  Widget getBodyWidget(BuildContext context) {
    return XWidgetUtils.getLayoutContainer(
        alignment: Alignment.topCenter,
        padding: XWidgetUtils.getEdgeInsets(0, 100, 0, 0),
        child: XWidgetUtils.getLayoutColumn(
            crossAxisAlignment :CrossAxisAlignment.center,
            children: [
              XWidgetUtils.getWidgetText(
                  '¥${XNumberUtils.formatDoubleX(RBBusinessUtils.shoppingcartInfo_selfService['totalMoney']??0, n: 2)}',
                  style: XStyleUtils.getTextStyle(
                      fontSize: 60,
                      color: XColorUtils.color333333,
                      fontWeight: FontWeight.bold
                  )
              ),
              XWidgetUtils.getLayoutContainer(
                  alignment: Alignment.center,
                  child: XWidgetUtils.getLayoutRow(
                      mainAxisSize:MainAxisSize.min,
                      mainAxisAlignment:MainAxisAlignment.center,
                      children: [
                        XWidgetUtils.getWidgetText(
                            XNumberUtils.formatDoubleX(RBBusinessUtils.shoppingcartInfo_selfService['totalQuantity']??0, n: 0),
                            style: XStyleUtils.getTextStyle(
                              fontSize: 50,
                              color: const Color(0xFFFF0020),
                            )
                        ),
                        XWidgetUtils.getWidgetText(
                            '件商品',
                            style: XStyleUtils.getTextStyle(
                              fontSize: 40,
                              color: XColorUtils.color999999,
                            )
                        ),
                      ]
                  )
              ),
              XWidgetUtils.getWidgetText(
                '请在下方扫码区扫描付款码',
                style: XStyleUtils.getTextStyle(
                  fontSize: 40,
                  color: XColorUtils.color333333,
                ),
                padding: XWidgetUtils.getEdgeInsets(0, 188, 0, 0),
              ),
              XWidgetUtils.getLayoutContainer(
                  margin: XWidgetUtils.getEdgeInsets(50, 21, 50, 0),
                  alignment: Alignment.center,
                  height: 693,
                  child: XWidgetUtils.getLayoutStack(
                      alignment:AlignmentDirectional.center,
                      children: [
                        XImageUtils.getImageWidgetWithAsset(
                          'ss_pay_bg_logo.png',
                          width: 501,
                          height: 560,
                        ),
                        isPayWaiting?XWidgetUtils.getXLayoutRoundedRect(
                            radius_topLeft: 30,
                            radius_topRight: 30,
                            radius_bottomRight: 30,
                            radius_bottomLeft: 30,
                            backgroundColor: const Color(0x66000000),
                            alignment: Alignment.center,
                            height: 693,
                            width: double.infinity,
                            child: XWidgetUtils.getWidgetTimerButton(
                                timeout_s: 15,
                                defaultName: '等待支付结果...',
                                fontColor: Colors.white,
                                fontSize: 50,
                                fontWeight: FontWeight.bold,
                                defaultBackgroundColor:Colors.transparent,
                                isAutoStart: true,
                                tag_action_receive_notify:RBConfigs.Tag_action_receive_notify_pay_wait_check,
                                onClick: (r1){
                                  checkTimer?.cancel();
                                  startPage(PageStateSelfServicePayResult(false),isFinish: true);
                                },
                                onTimerComplete: (r1){
                                  checkTimer?.cancel();
                                  startPage(PageStateSelfServicePayResult(false),isFinish: true);
                                }
                            ),
                        ):XWidgetUtils.getLayoutContainer()
                      ]
                  )
              ),

              XWidgetUtils.getWidgetText(
                '支持支付方式',
                style: XStyleUtils.getTextStyle(
                  fontSize: 40,
                  color: XColorUtils.color333333,
                ),
                padding: XWidgetUtils.getEdgeInsets(0, 76, 0, 0),
              ),
              XWidgetUtils.getLayoutContainer(
                  margin: XWidgetUtils.getEdgeInsets(165, 40, 165, 0),
                  child: XWidgetUtils.getLayoutRow(
                      children: [
                        XWidgetUtils.getLayoutExpanded(
                            XWidgetUtils.getLayoutContainer(
                                backgroundColor: Colors.white,
                                alignment: Alignment.center,
                                child: XWidgetUtils.getLayoutRow(
                                    mainAxisAlignment:MainAxisAlignment.center,
                                    children: [
                                      XImageUtils.getImageWidgetWithAsset(
                                        'ss_pay_weixin.png',
                                        width: 121,
                                        height: 120,
                                      ),
                                      XWidgetUtils.getWidgetText(
                                          '微信支付',
                                          style: XStyleUtils.getTextStyle(
                                            fontSize: 40,
                                            color: XColorUtils.color333333,
                                          ),
                                          padding: XWidgetUtils.getEdgeInsets(21, 0, 0, 0)
                                      )
                                    ]
                                )
                            )
                        ),
                        XWidgetUtils.getLayoutExpanded(
                            XWidgetUtils.getLayoutContainer(
                                backgroundColor: Colors.white,
                                alignment: Alignment.center,
                                child: XWidgetUtils.getLayoutRow(
                                    mainAxisAlignment:MainAxisAlignment.center,
                                    children: [
                                      XImageUtils.getImageWidgetWithAsset(
                                        'ss_pay_zhifubao.png',
                                        width: 121,
                                        height: 120,
                                      ),
                                      XWidgetUtils.getWidgetText(
                                          '支付宝支付',
                                          style: XStyleUtils.getTextStyle(
                                            fontSize: 40,
                                            color: XColorUtils.color333333,
                                          ),
                                          padding: XWidgetUtils.getEdgeInsets(21, 0, 0, 0)
                                      )
                                    ]
                                )
                            )
                        ),
                      ]
                  )
              ),
              XWidgetUtils.getLayoutContainer(
                  margin: XWidgetUtils.getEdgeInsets(0, 108, 0, 0),
                  alignment: Alignment.center,
                  child: XWidgetUtils.getLayoutRow(
                      mainAxisAlignment:MainAxisAlignment.center,
                      children: [
                        XWidgetUtils.getWidgetText(
                          '请在 ',
                          style: XStyleUtils.getTextStyle(
                            fontSize: 40,
                            color: XColorUtils.color333333,
                          ),
                        ),
                        XWidgetUtils.getWidgetTimerButton(
                            timeout_s: 120,
                            fontColor: const Color(0xFFFF0020),
                            fontSize: 40,
                            defaultBackgroundColor:Colors.white,
                            isAutoStart: true,
                            tag_action_receive_notify:RBConfigs.Tag_action_receive_notify_pay_auto_exit,
                            onClick: (r1){
                              startPage(PageStateSelfServicePayResult(false),isFinish: true);
                            },
                            onTimerComplete: (r1){
                              startPage(PageStateSelfServicePayResult(false),isFinish: true);
                            }
                        ),
                        XWidgetUtils.getWidgetText(
                          ' 内完成支付',
                          style: XStyleUtils.getTextStyle(
                            fontSize: 40,
                            color: XColorUtils.color333333,
                          ),
                        ),
                      ]
                  )
              ),

            ]
        )
    );
  }


  @override
  void finishPage({result, String? backToPointPageName}) {
    notifyExitButtonStopTimer(RBConfigs.Tag_action_receive_notify_pay_auto_exit);
    notifyExitButtonStopTimer(RBConfigs.Tag_action_receive_notify_pay_wait_check);
    super.finishPage(result:result, backToPointPageName:backToPointPageName);
  }


  @override
  Future<void> updateData({int pageIndex = 1}) async {

  }


  @override
  Color getXPageBackgroundColor() {
    return Colors.white;
  }


  void notifyExitButtonRestartTimer(String action){
    XNotifyStateChangeUtils.notifyStateChange(
        action: action,
        key: 'restartTimer',
        value: 'value'
    );
  }
  void notifyExitButtonStopTimer(String action){
    XNotifyStateChangeUtils.notifyStateChange(
        action: action,
        key: 'stopTimer',
        value: 'value'
    );
  }

}